package com.ny.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ny.entity.SensorData;
import com.ny.repository.SensorDataRepository;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Service;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.TextMessage;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

@Service
public class AmqpMessageReceiver {

    private final SensorDataRepository sensorDataRepository;
    // 华为云时间格式解析器（带时区）
    private static final SimpleDateFormat HUAWEI_TIME_FORMAT = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
    private static final SimpleDateFormat DISPLAY_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    static {
        HUAWEI_TIME_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); // 华为云时间是UTC时区
    }

    public AmqpMessageReceiver(SensorDataRepository sensorDataRepository) {
        this.sensorDataRepository = sensorDataRepository;
    }

    @JmsListener(destination = "#{queueName}")
    public void receiveMessage(Message message) throws JMSException {
        try {
            TextMessage textMessage = (TextMessage) message;
            String messageContent = textMessage.getText();
            // 解析消息
            SensorData sensorData = parseMessage(messageContent);
            if (sensorData != null) {
                sensorDataRepository.save(sensorData);
                // 格式化输出接收到的数据
                System.out.println("=== 设备数据报告 ===");
                System.out.println("设备ID: " + sensorData.getDeviceId());
                System.out.println("温度: " + String.format("%.2f°C", sensorData.getTemperature()));
                System.out.println("湿度: " + String.format("%.2f%%", sensorData.getHumidity()));
                if (sensorData.getDeviceTime() != null) {
                    System.out.println("设备时间: " + DISPLAY_FORMAT.format(sensorData.getDeviceTime()));
                }
                System.out.println("接收时间: " + DISPLAY_FORMAT.format(sensorData.getReceiveTime()));
                System.out.println("==================");
            }
            message.acknowledge(); // 确认消息处理完成
        } catch (Exception e) {
            System.err.println("处理消息出错: " + e.getMessage());
            e.printStackTrace();
        }
    }
    private SensorData parseMessage(String messageContent) {
        try {
            JSONObject root = JSON.parseObject(messageContent);
            // 打印格式化的消息摘要
            printFormattedMessage(root);
            // 1. 获取设备ID（从notify_data.header中提取）
            JSONObject notifyData = root.getJSONObject("notify_data");
            if (notifyData == null) {
                System.err.println("消息中没有notify_data字段");
                return null;
            }
            JSONObject header = notifyData.getJSONObject("header");
            String deviceId = header.getString("device_id");
            if (deviceId == null) {
                System.err.println("消息中没有device_id字段");
                return null;
            }
            // 2. 获取传感器数据
            JSONObject body = notifyData.getJSONObject("body");
            if (body == null) {
                System.err.println("消息中没有body字段");
                return null;
            }
            JSONArray services = body.getJSONArray("services");
            if (services == null || services.isEmpty()) {
                System.err.println("消息中services数组为空");
                return null;
            }
            // 取第一个service（实际场景可能有多个，根据需求调整）
            JSONObject firstService = services.getJSONObject(0);
            JSONObject properties = firstService.getJSONObject("properties");
            if (properties == null) {
                System.err.println("消息中没有properties字段");
                return null;
            }
            // 3. 提取温度和湿度
            float temp = properties.getFloatValue("temp");
            float humi = properties.getFloatValue("humi");
            // 4. 解析设备发送时间（从service的event_time提取）
            String eventTimeStr = firstService.getString("event_time");
            Date deviceTime = null;
            if (eventTimeStr != null && !eventTimeStr.isEmpty()) {
                try {
                    deviceTime = HUAWEI_TIME_FORMAT.parse(eventTimeStr);
                } catch (ParseException e) {
                    System.err.println("解析设备时间失败: " + e.getMessage());
                }
            }
            // 5. 封装数据对象
            SensorData sensorData = new SensorData();
            sensorData.setDeviceId(deviceId);
            sensorData.setTemperature(temp);
            sensorData.setHumidity(humi);
            sensorData.setReceiveTime(new Date()); // 接收时间（本地服务器时间）
            sensorData.setDeviceTime(deviceTime); // 设备发送时间（UTC转换后）
            return sensorData;
        } catch (Exception e) {
            System.err.println("解析消息失败: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 格式化打印消息内容摘要
     */
    private void printFormattedMessage(JSONObject root) {
        try {
            String resource = root.getString("resource");
            String event = root.getString("event");
            String eventTime = root.getString("event_time");
            
            JSONObject notifyData = root.getJSONObject("notify_data");
            if (notifyData == null) return;
            
            JSONObject header = notifyData.getJSONObject("header");
            String deviceId = header != null ? header.getString("device_id") : "未知";
            
            JSONObject body = notifyData.getJSONObject("body");
            if (body == null) return;
            
            JSONArray services = body.getJSONArray("services");
            if (services == null || services.isEmpty()) return;
            
            JSONObject firstService = services.getJSONObject(0);
            JSONObject properties = firstService.getJSONObject("properties");
            
            if (properties == null) return;
            
            float temp = properties.getFloatValue("temp");
            float humi = properties.getFloatValue("humi");
            
            System.out.println("=== 接收到AMQP消息 ===");
            System.out.println("资源类型: " + resource);
            System.out.println("事件类型: " + event);
            System.out.println("事件时间: " + eventTime);
            System.out.println("设备ID: " + deviceId);
            System.out.println("温度: " + String.format("%.2f°C", temp));
            System.out.println("湿度: " + String.format("%.2f%%", humi));
            System.out.println("=====================");
        } catch (Exception e) {
            // 如果解析摘要失败，至少打印原始消息
            System.out.println("接收到消息: " + root.toJSONString());
        }
    }
}